<template>
  <div>
    <van-nav-bar left-arrow title="搜索结果" @click-left="$router.back()" />

    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        offset="50"
        @load="onLoad"
      >
        <article-item
          v-for="item in articleList"
          :key="item.art_id"
          :obj="item"
          :showX=false
          @click.native="$router.push(`/article_detail?aid=${item.art_id}`)"
        />
      </van-list>
    </div>
  </div>
</template>

<script>
import { searchResultsApi } from '@/api'
import { timeAgo } from '@/utils/date.js'
import ArticleItem from '@/views/Second/Home/components/ArticleItem.vue'
export default {
  name: 'SearchResult',
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      page: 1
    }
  },
  methods: {
    onLoad () {
      // 解决刚进入页面，会请求两次数据的问题
      // 当created钩子请求后获得数据，再次下拉才会请求数据
      // if (this.articleList.length > 0) {
      this.getArticlesList()
      // }
      // console.log(1)
    },
    async getArticlesList () {
      const res = await searchResultsApi({
        q: this.$route.params.keywords,
        page: this.page
      })
      res.data.data.results.forEach((item) => {
        item.pubdate = timeAgo(item.pubdate)
      })
      // console.log(res.data.data)
      // this.articleList = res.data.data.results
      if (res.data.data.results.length === 0) {
        this.loading = false
        this.finished = true // 当接口返回数据为空，则不再加载，停止调用接口
      } else {
        this.page++
        this.articleList = [...this.articleList, ...res.data.data.results]
        this.loading = false
      }
    }
  },
  created () {
    this.getArticlesList()
  },
  components: {
    ArticleItem
  }
}
</script>

<style lang="scss" scoped>
</style>
